//
//  BootAnimationViewController.m
//  boot
//
//  Created by Demi on 07/03/2017.
//  Copyright © 2017 Azazie. All rights reserved.
//

#import "BootAnimationViewController.h"

#import "BootWindow.h"
#import "UIImage+Gif.h"
#import "GifImageView.h"
#import "UIImageView+Gif.h"
#import "BootAnimationView.h"
#import "BootSpreadImageCenterView.h"

#import <base/base.h>

#import <Masonry/Masonry.h>
#import <ImageIO/ImageIO.h>
#import <ReactiveObjC/ReactiveObjC.h>
#import <SMPageControl/SMPageControl.h>

#define IS_SMALL_LAYOUT ([UIScreen mainScreen].bounds.size.height <= 480.f)
#define MARGIN (IS_SMALL_LAYOUT ? 20.f : 40.f)

#define IMAGE_SIZE (IS_SMALL_LAYOUT ? CGSizeMake(210.f, 180.f) : CGSizeMake(295.f, 250.f))

#define IS_HEIGHT_WIDTH_3_2 ([UIScreen mainScreen].bounds.size.height / [UIScreen mainScreen].bounds.size.width == 1.5f)

#define IS_FOR_LOVEPROM_APP ((self.bootWindow.configuration.type==BootTypeAnimatingAndGuideForLP) || (self.bootWindow.configuration.type==BootTypeAnimatingOnlyForLP))
#define IS_SHOULD_GUIDE     ((self.bootWindow.configuration.type==BootTypeAnimatingAndGuideForLP) || (self.bootWindow.configuration.type==BootTypeAnimatingAndGuide))

#define KIsiPhoneX ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size) : NO)

@interface BootAnimationViewController () <UIGestureRecognizerDelegate, UIScrollViewDelegate>

@property (nonatomic, weak) UIView *backgroundView;

@property (nonatomic, weak, readonly) SMPageControl *pageControl;
@property (nonatomic, weak, readonly) UIButton *signInButton;
@property (nonatomic, weak, readonly) UIButton *signUpButton;
@property (nonatomic, weak, readonly) UIButton *skipButton;

@property (nonatomic, assign, readonly) NSUInteger numberOfPages;
@property (nonatomic, assign) NSUInteger lastScrolledPage;
@property (nonatomic, weak, readonly) UIScrollView *pagingScrollView;

@property (nonatomic, copy) NSArray<GifImageView *> *gifImageViews;

@property (nonatomic, weak) BootWindow *bootWindow;

@end

@implementation BootAnimationViewController

- (instancetype)initWithWindow:(BootWindow *)window
{
    self = [super initWithNibName:nil bundle:nil];
    if (self)
    {
        self.bootWindow = window;
        [[[NSNotificationCenter defaultCenter] rac_addObserverForName:AccessTokenDidChangeNotification object:nil] subscribeNext:^(NSNotification * _Nullable x) {
            if ([AccessToken currentAccessToken] != nil) {
                _signInButton.hidden = YES;
                _signUpButton.hidden = YES;
            }
        }];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor clearColor];
    if (IS_SHOULD_GUIDE)
    {
        if (self.bootWindow.configuration.type==BootTypeAnimatingAndGuideForLP) {
            [self configurePagingScrollViewForLP];
            [self configureInteractiveViewsForLP];
        } else {
            UIView *backgroundView = [[UIView alloc] init].tx_backgroundColorHex(0xececec);
            _backgroundView = backgroundView;
            [self.view addSubview:backgroundView];
            [backgroundView mas_makeConstraints:^(MASConstraintMaker *maker){
                maker.edges.mas_equalTo(UIEdgeInsetsZero);
            }];
            [self configurePagingScrollView];
            [self configureInteractiveViews];
            [self configureForiPhoneX];
        }
    }
    [self configureAnimation];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return IS_FOR_LOVEPROM_APP ? UIStatusBarStyleLightContent : UIStatusBarStyleDefault;
}

#pragma mark - action

- (void)translationViewsWithOffset:(CGFloat)offset
{
    CGAffineTransform transform;
    if (offset <= 0)
    {
        transform = CGAffineTransformIdentity;
    }
    else
    {
        transform = CGAffineTransformMakeTranslation(-offset, 0);
    }
    self.signInButton.transform = transform;
    self.signUpButton.transform = transform;
    self.pageControl.transform = transform;
    self.skipButton.transform = transform;
    self.backgroundView.transform = transform;
}

#pragma mark - configure for iphoneX
- (void)configureForiPhoneX {
    if (@available(iOS 11.0, *)) {
        @weakify(self);
        [[self.view rac_signalForSelector:@selector(safeAreaInsetsDidChange)] subscribeNext:^(RACTuple * _Nullable x) {
            @strongify(self);
            if (self.view.safeAreaInsets.top > 0) {
                [self.skipButton mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.top.equalTo(self.view).offset(self.view.safeAreaInsets.top + 25.f);
                }];
                [self.pagingScrollView mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.edges.mas_equalTo(UIEdgeInsetsMake(self.view.safeAreaInsets.top, 0, 0, 0));
                }];
            }
            if (self.view.safeAreaInsets.bottom > 0) {
                [self.signInButton mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.bottom.mas_equalTo(-20 - self.view.safeAreaInsets.bottom);
                }];
            }
        }];
    }
}

#pragma mark - configure PagingScrollView
- (void)configurePagingScrollView
{
    UIScrollView *scrollView = [[TXTouchableScrollView alloc] initWithFrame:CGRectZero];
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.bounces = NO;
    scrollView.scrollsToTop = NO;
    scrollView.pagingEnabled = YES;
    scrollView.delegate = self;
    _pagingScrollView = scrollView;
    [self.view addSubview:scrollView];
    [scrollView mas_makeConstraints:^(MASConstraintMaker *maker){
        maker.edges.mas_equalTo(UIEdgeInsetsZero);
    }];
    
    NSArray<NSDictionary *> *items = @[@{@"img": @"bootstrap_affordable", @"title": @"Affordable Bridesmaid Dresses", @"subtitle": @"We source and design everything in-house to keep prices low."},
                       @{@"img": @"bootstrap_sample", @"title": @"Convenient Try at Home Program", @"subtitle": @"Before you buy, try on our sample to pick the right size."},
                       @{@"img": @"bootstrap_customsize", @"title": @"Unique Custom Size Service", @"subtitle": @"Dresses can be custom tailored and sewn to flatter your figure."}];
    
    NSBundle *bundle = [NSBundle bundleWithPath:[[NSBundle bundleForClass:[self class]] pathForResource:@"bootanimate" ofType:@"bundle"]];
    NSString *imageNameSuffix = IS_HEIGHT_WIDTH_3_2 ? @"640" : @"750";
    NSArray *views = [items tx_map:^(NSDictionary *item){
        UIView *contentView = [[UIView alloc] init];
        
        NSString *path = [bundle pathForResource:[item[@"img"] stringByAppendingString:imageNameSuffix] ofType:@"gif"];
        
        GifImageView *imageView = [[GifImageView alloc] initWithFrame:CGRectZero];
        imageView.gifPath = path;
        [imageView displayFirstFrame];
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        [contentView addSubview:imageView];
        [imageView mas_makeConstraints:^(MASConstraintMaker *maker){
            maker.centerX.equalTo(contentView);
            maker.top.mas_equalTo(IS_SMALL_LAYOUT ? 45.f : 75.f);
            maker.size.mas_equalTo(IMAGE_SIZE);
        }];
        
        UILabel *label = [[UILabel alloc] init];
        label.tx_textColorHex(0x121212)
             .tx_boldSystemFont(UIFontExtraLargeSize)
             .tx_textAlignment(NSTextAlignmentCenter)
             .tx_text(item[@"title"]);
        label.font=[UIFont fontWithName:@"Arimo-Regular" size:18];
        [contentView addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *maker){
            maker.left.mas_equalTo(MARGIN);
            maker.right.mas_equalTo(-MARGIN);
            maker.top.equalTo(imageView.mas_bottom).offset(IS_SMALL_LAYOUT ? 15.f : 25.f);
        }];
        
        UILabel *sublabel = [[UILabel alloc] init];
        sublabel.tx_textColorHex(0x121212)
                .tx_systemFont(UIFontSmallSize)
                .tx_textAlignment(NSTextAlignmentCenter)
                .tx_numberOfLines(0)
                .tx_text(item[@"subtitle"]);
        [contentView addSubview:sublabel];
        [sublabel mas_makeConstraints:^(MASConstraintMaker *maker){
            maker.left.and.right.equalTo(imageView);
            maker.top.equalTo(label.mas_bottom).offset(5.f);
        }];
        
        return contentView;
    }];
    
    self.gifImageViews = [views tx_map:^(UIView *view){
        for (UIView *subview in view.subviews)
        {
            if ([subview isKindOfClass:[GifImageView class]])
            {
                return subview;
            }
        }
        return view;
    }];
    
    NSMutableArray *pages = [NSMutableArray arrayWithArray:views];
    [pages addObject:[[UIView alloc] init].tx_backgroundColor([UIColor clearColor])];
    [scrollView setPages:pages];
    _numberOfPages = pages.count;
    _lastScrolledPage = 0;
}

- (void)configurePagingScrollViewForLP {
    UIScrollView *scrollView = [[TXTouchableScrollView alloc] initWithFrame:CGRectZero];
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.bounces = NO;
    scrollView.scrollsToTop = NO;
    scrollView.pagingEnabled = YES;
    scrollView.delegate = self;
    _pagingScrollView = scrollView;
    [self.view addSubview:scrollView];
    [scrollView mas_makeConstraints:^(MASConstraintMaker *maker){
        maker.edges.mas_equalTo(UIEdgeInsetsZero);
    }];
    
    NSArray<NSDictionary *> *items = @[@{@"img": @"bootstrap_first"},
                                       @{@"img": @"bootstrap_second"},
                                       @{@"img": @"bootstrap_third"}];
    
    NSBundle *bundle = [NSBundle bundleWithPath:[[NSBundle bundleForClass:[self class]] pathForResource:@"bootanimate" ofType:@"bundle"]];
    NSString *imageNameSuffix = IS_HEIGHT_WIDTH_3_2 ? @"640" : @"750";
    if (KIsiPhoneX) {
        imageNameSuffix = @"1624";
    }
    NSArray *views = [items tx_map:^(NSDictionary *item){
        UIView *contentView = [[UIView alloc] init];
        contentView.backgroundColor = [UIColor blackColor];
        
        NSString *path = [bundle pathForResource:[item[@"img"] stringByAppendingString:imageNameSuffix] ofType:@"png"];
        
        GifImageView *imageView = [[GifImageView alloc] initWithImage:[[UIImage alloc] initWithContentsOfFile:path]];
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        [contentView addSubview:imageView];
        [imageView mas_makeConstraints:^(MASConstraintMaker *maker){
            maker.edges.mas_equalTo(UIEdgeInsetsZero);
        }];
        
        return contentView;
    }];
    
    self.gifImageViews = [views tx_map:^(UIView *view){
        for (UIView *subview in view.subviews)
        {
            if ([subview isKindOfClass:[UIImageView class]])
            {
                return subview;
            }
        }
        return view;
    }];
    
    NSMutableArray *pages = [NSMutableArray arrayWithArray:views];
    [pages addObject:[[UIView alloc] init].tx_backgroundColor([UIColor clearColor])];
    [scrollView setPages:pages];
    _numberOfPages = pages.count;
    _lastScrolledPage = 0;
}


#pragma mark - configure InteractiveView
- (void)configureInteractiveViews
{
    // skip button
    UIButton *skipButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _skipButton = skipButton;
    [self.view addSubview:skipButton];
    [skipButton setTitle:@"SKIP" forState:UIControlStateNormal];
    skipButton.titleLabel.font = [UIFont systemFontOfSize:UIFontNormalSize];
    [skipButton setTitleColor:[UIColor tx_colorWithHex:0xc9ab97] forState:UIControlStateNormal];
    [skipButton mas_makeConstraints:^(MASConstraintMaker *maker){
        maker.top.equalTo(self.view).offset(25.f);
        maker.right.equalTo(self.view).offset(-25.f);
    }];
    @weakify(self);
    [[skipButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x){
        @strongify(self);
        [self.bootWindow dismissWithStyle:BootDismissalAnimationStyleLeftTransition];
    }];
    
    // sign in & sign up
    UIButton *signInButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _signInButton = signInButton;
    NSAttributedString *signInAttributedText =
    [[NSAttributedString alloc] initWithString:@"Sign in"
                                    attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:UIFontNormalSize],
                                                 NSForegroundColorAttributeName: [UIColor darkGrayTextColor]}];
    [signInButton setAttributedTitle:signInAttributedText forState:UIControlStateNormal];
    [self.view addSubview:signInButton];
    [signInButton mas_makeConstraints:^(MASConstraintMaker *maker){
        maker.left.mas_equalTo(MARGIN);
        maker.right.mas_equalTo(-MARGIN);
        maker.bottom.mas_equalTo(-20.f);
    }];
//    UIButton *signUpButton = [UIButton primaryButton];
    UIButton *signUpButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [signUpButton setBackgroundColor:[UIColor colorWithRed:18.f/255.f green:18.f/255.f blue:18.f/255.f alpha:1]];
    _signUpButton = signUpButton;
    [self.view addSubview:signUpButton];
    [signUpButton setTitle:@"SIGN UP" forState:UIControlStateNormal];
    [signUpButton mas_makeConstraints:^(MASConstraintMaker *maker){
        maker.bottom.equalTo(signInButton.mas_top).offset(-10.f);
        maker.height.mas_equalTo(44.f);
        maker.left.and.right.equalTo(signInButton);
    }];

    if (self.bootWindow.configuration.hasSignedIn)
    {
        signInButton.hidden = YES;
        signUpButton.hidden = YES;
    }
    else
    {
        @weakify(self);
        [[signInButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x){
            @strongify(self);
            self.bootWindow.configuration.signInCallback();
        }];
        [[signUpButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x){
            @strongify(self);
            self.bootWindow.configuration.signUpCallback();
        }];
    }
    
    // page control
    SMPageControl *pageControl = [[SMPageControl alloc] init];
    _pageControl = pageControl;
    [self.view addSubview:pageControl];
    [pageControl mas_makeConstraints:^(MASConstraintMaker *maker){
        maker.left.and.right.mas_equalTo(0.f);
        maker.bottom.equalTo(signUpButton.mas_top).offset(-30.f);
    }];
    pageControl.numberOfPages = self.numberOfPages - 1;
    pageControl.currentPage = 0;
    pageControl.enabled = NO;
    pageControl.currentPageIndicatorImage = [UIImage tx_imageWithColor:[UIColor tx_colorWithHex:0x121212]
                                                                  size:CGSizeMake(8.f, 8.f)
                                                               ellipse:YES];
    pageControl.pageIndicatorImage = [UIImage tx_imageWithColor:[UIColor tx_colorWithHex:0xcccccc]
                                                           size:CGSizeMake(8.f, 8.f)
                                                        ellipse:YES];
}

- (void)configureInteractiveViewsForLP {
    // skip button
    UIButton *skipButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _skipButton = skipButton;
    [self.view addSubview:skipButton];
    [skipButton setImage:[UIImage imageNamed:@"guide page_close"] forState:UIControlStateNormal];
    skipButton.titleLabel.font = [UIFont systemFontOfSize:UIFontNormalSize];
    [skipButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [skipButton mas_makeConstraints:^(MASConstraintMaker *maker){
        maker.top.equalTo(self.view).offset(25.f);
        maker.right.equalTo(self.view).offset(-10.f);
    }];
    @weakify(self);
    [[skipButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x){
        @strongify(self);
        [self.bootWindow dismissWithStyle:BootDismissalAnimationStyleLeftTransition];
    }];
    
    // sign in & sign up
    UIButton *signInButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _signInButton = signInButton;
    NSMutableAttributedString *signInAttributedText =
    [[NSMutableAttributedString alloc] initWithString:@"Sign In"
                                    attributes:@{NSForegroundColorAttributeName: [UIColor whiteColor],
                                                 NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle),
                                                 NSFontAttributeName : [UIFont dynamic_fontWithName:FunctionProDemi size:15.f]
                                                 }];
    [signInButton setAttributedTitle:signInAttributedText forState:UIControlStateNormal];
    [self.view addSubview:signInButton];
    [signInButton mas_makeConstraints:^(MASConstraintMaker *maker){
        maker.left.mas_equalTo(15);
        maker.right.mas_equalTo(-15);
        maker.bottom.mas_equalTo(-50.f);
    }];
    
    
    UIButton *signUpButton = [UIButton buttonWithType:UIButtonTypeCustom];
    UIFont *font = [UIFont dynamic_fontWithName:FunctionProDemi size:UIFontLargeSize];
    UIColor *normal = [UIColor tx_colorWithHex:LPPrimaryButtonBackgroundColorHex];
    UIColor *highlited = [UIColor tx_colorWithHex:LPPrimaryButtonHighlightedBackgroundColorHex];
    UIColor *disabled = [UIColor tx_colorWithHex:PrimaryButtonDisabledBackgroundColorHex];
    [signUpButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    signUpButton.titleLabel.font = font;
    [signUpButton setBackgroundImage:[UIImage tx_imageWithColor:normal] forState:UIControlStateNormal];
    [signUpButton setBackgroundImage:[UIImage tx_imageWithColor:highlited] forState:UIControlStateHighlighted];
    [signUpButton setBackgroundImage:[UIImage tx_imageWithColor:disabled] forState:UIControlStateDisabled];
    signUpButton.layer.cornerRadius = 3.f;
    signUpButton.layer.masksToBounds = YES;
    _signUpButton = signUpButton;
    [self.view addSubview:signUpButton];
    [signUpButton setTitle:@"Sign Up" forState:UIControlStateNormal];
    [signUpButton mas_makeConstraints:^(MASConstraintMaker *maker){
        maker.bottom.equalTo(signInButton.mas_top).offset(-15.f);
        maker.height.mas_equalTo(45.f);
        maker.left.and.right.equalTo(signInButton);
    }];
    
    
    if (self.bootWindow.configuration.hasSignedIn)
    {
        signInButton.hidden = YES;
        signUpButton.hidden = YES;
    }
    else
    {
        @weakify(self);
        [[signInButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x){
            @strongify(self);
            self.bootWindow.configuration.signInCallback();
        }];
        [[signUpButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x){
            @strongify(self);
            self.bootWindow.configuration.signUpCallback();
        }];
    }
    
    // page control
    SMPageControl *pageControl = [[SMPageControl alloc] init];
    _pageControl = pageControl;
    [self.view addSubview:pageControl];
    [pageControl mas_makeConstraints:^(MASConstraintMaker *maker){
        maker.left.and.right.mas_equalTo(0.f);
        maker.bottom.equalTo(signUpButton.mas_top).offset(0);
    }];
    pageControl.numberOfPages = self.numberOfPages - 1;
    pageControl.currentPage = 0;
    pageControl.enabled = NO;
    UIImage *currenrPage =
    pageControl.currentPageIndicatorImage = [UIImage circleImageWithSize:CGSizeMake(6.f, 6.f)
                                                                   color:[UIColor whiteColor]
                                                             borderWidth:1.f
                                                             borderColor:[UIColor blackColor]];
    pageControl.pageIndicatorImage = [UIImage circleImageWithSize:CGSizeMake(6.f, 6.f)
                                                            color:[UIColor blackColor]
                                                      borderWidth:1.f
                                                      borderColor:[UIColor whiteColor]];
}

#pragma mark - configure animation
- (void)configureAnimation
{
    NSBundle *bundle = [NSBundle bundleWithPath:[[NSBundle bundleForClass:[self class]] pathForResource:@"bootanimate" ofType:@"bundle"]];
    NSString *imageNameSuffix = IS_HEIGHT_WIDTH_3_2 ? @"640" : @"750";
    NSString *imageName = IS_FOR_LOVEPROM_APP?@"boot_lp":@"boot";
    // 一张图片新代码
    imageName = @"boot_icon";
    NSString *path = [bundle pathForResource:[imageName stringByAppendingString:imageNameSuffix] ofType:@"jpeg"];
//    NSTimeInterval duration = 0;
//    NSArray *images = [UIImage imagesWithContentsOfFile:path duration:&duration];
    
//    BootSpreadImageCenterView *spreadView = [[BootSpreadImageCenterView alloc] initWithFrame:self.view.bounds image:images.lastObject];
//    BootSpreadImageCenterView *spreadView = [[BootSpreadImageCenterView alloc] initWithFrame:self.view.bounds image:[UIImage imageWithContentsOfFile:path]];
//    [self.view addSubview:spreadView];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.backgroundColor = [UIColor redColor];
    [imageView setImage:[UIImage imageWithContentsOfFile:path]];
    [self.view addSubview:imageView];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [imageView removeFromSuperview];
        if (!IS_SHOULD_GUIDE) {
            [self.bootWindow dismissWithStyle:BootDismissalAnimationStyleNone];
        }
    });
    // 下面是gif 老代码
//    NSString *path = [bundle pathForResource:[imageName stringByAppendingString:imageNameSuffix] ofType:@"gif"];
//    NSTimeInterval duration = 0;
//    NSArray *images = [UIImage imagesWithContentsOfFile:path duration:&duration];
//    
//    BootSpreadImageCenterView *spreadView = [[BootSpreadImageCenterView alloc] initWithFrame:self.view.bounds image:images.lastObject];
//    [self.view addSubview:spreadView];
//    
//    UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
//    imageView.contentMode = UIViewContentModeScaleAspectFill;
//    [self.view addSubview:imageView];
//    
//    @weakify(self);
//    [imageView startAnimatingWithImages:images duration:duration completion:^{
//        [imageView removeFromSuperview];
//        void(^finished)(BOOL) = ^(BOOL isAzazie) {
//            @strongify(self);
//            if (IS_SHOULD_GUIDE) {
//                [UIView animateWithDuration:BOOT_WINDOW_ANIMATION_DURATION animations:^{
//                    spreadView.alpha = 0;
//                } completion:^(BOOL finished) {
//                    [spreadView removeFromSuperview];
//                    [self.gifImageViews.firstObject start];
//                }];
//            } else {
//                [self.bootWindow dismissWithStyle:isAzazie?BootDismissalAnimationStyleNone:BootDismissalAnimationStyleFadeOut];
//            }
//        };
//        if (IS_FOR_LOVEPROM_APP) {
//            finished(NO);
//        } else {
//            [spreadView animateWithCompletion:^{
//                finished(YES);
//            }];
//        }
//    }];
}

#pragma mark - page

- (NSUInteger)currentPageIndex
{
    CGFloat offsetX = self.pagingScrollView.contentOffset.x;
    
    if (offsetX < 0) return 0;
    
    return (NSUInteger)floor(offsetX / self.pagingScrollView.bounds.size.width);
}

- (BOOL)isLastPage
{
    return [self currentPageIndex] == self.numberOfPages - 1;
}

- (void)scrollDidEnd
{
    if ([self isLastPage])
    {
        [self.bootWindow dismissWithStyle:BootDismissalAnimationStyleNone];
    }
    else
    {
        NSUInteger currentPage = [self currentPageIndex];
        if (currentPage != _lastScrolledPage)
        {
            _lastScrolledPage = currentPage;
        }
        [self.gifImageViews enumerateObjectsUsingBlock:^(GifImageView *imageView, NSUInteger idx, BOOL *stop){
            if (currentPage == idx)
            {
                if (!IS_FOR_LOVEPROM_APP) {
                    [imageView start];
                }
            }
            else
            {
                if (!IS_FOR_LOVEPROM_APP) {
                    [imageView suspend];
                    [imageView displayFirstFrame];
                }
            }
        }];
        self.pageControl.currentPage = [self currentPageIndex];
        [self translationViewsWithOffset:0.f];
    }
}

#pragma mark - scroll View

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (!decelerate)
    {
        [self scrollDidEnd];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self scrollDidEnd];
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    [self scrollDidEnd];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat baseline = (self.numberOfPages - 1) * scrollView.tx_width;
    [self translationViewsWithOffset:scrollView.contentOffset.x + scrollView.tx_width  - baseline];
}

@end
